import { post, get} from '@/utils/request';
import {API_ADDRESS, API_PAY_ADDRESS, IMG_URI_ADDRESS} from "@/api/api";
import {version, name} from '/package.json';
import { getCurrentTimeStamp} from "@/utils/time/timeUtils";
import { initBrowserVersion, getOperationSystem} from "@/utils/rest/browserVersion";
import {
    basicAccountModel,
    userDeviceListModel,
    userApiKeyFilterModel,
    sendVerifyCodeModel,
    forgetPassModel,
    registerModel,
    PayCallParam,
    payAttachFilter, OneField
} from "@/api/entity/RequestParam";
import { getResultAddress } from "@/api/entity/ResultParam";
import { useUserStore } from "@/store";
import {ignoreENOENT} from "rimraf/dist/mjs/ignore-enoent";

const userStore = useUserStore();



/**
 * 获取设备编号
 */
function getDeviceId() {
   return localStorage.getItem("visitorId")
}

function getStoreUserId() {
    const user:User.saveUserInfo = userStore.getAppointUserInfo();
    if (user === undefined || user === null) {
        return '';
    }
    if (user.userBasic === null) {
        return '';
    }
    return user.userBasic.id;
}

function builderRequestParam(data: any) {
    const commonAskParam = {
        userId: getStoreUserId(),
        deviceId: getDeviceId(),
        appVersion: version,
        pageName: name,
        osType: "Web",
        deviceModel: getOperationSystem(),
        osAppVersion: initBrowserVersion(),
        currentTime: getCurrentTimeStamp()
    }
    return {
        common: commonAskParam,
        data: data
    }
};
/**
 * 登录
 */
export const loginAPI = (data: basicAccountModel) => {
     return post<User.saveUserInfo>({
        url: API_ADDRESS.LOGIN,
        data: builderRequestParam(data)
    })
}
/**
 * 验证码登录
 * @param data
 */
export const loginVerifyAPI = (data: basicAccountModel) => {
    return post<User.saveUserInfo>({
        url: API_ADDRESS.USE_VERIFY_LOGIN,
        data: builderRequestParam(data)
    })
}


/**
 * 获取验证码接口
 */
export const getVerifyCodeAPI =  (data: sendVerifyCodeModel) => {
    return post({
        url: API_ADDRESS.SEND_VERIFY_CODE,
        data: builderRequestParam(data)
    })
}
/**
 * 忘记密码, 找回密码功能
 */
export const forgetPwdAPI = (data: forgetPassModel) => {
    return post({
        url: API_ADDRESS.FORGET_PWD,
        data: builderRequestParam(data)
    })
}

/**
 * 注册
 */
export const registerAccountAPI =  (data: registerModel) => {
    return  post({
        url: API_ADDRESS.REGISTER_ACCOUNT,
        data: builderRequestParam(data)
    })
}

/**
 * 创建用户的apiKey
 */
export const createApiKeyAPI = (data: {name: string}) => {
    return post({
        url: API_ADDRESS.CREATE_API_KEY,
        data: builderRequestParam(data)
    })
}





/**
 * 修改用户登录密码
 */
export const updateUserLoginPwd = () => {

}

/**
 * 解除三方登录方式
 */
export const unbindAuthLoginMethod = () => {

}

/**
 * 绑定三方登录方式
 */
export const bindAuthLoginMethod = () => {

}

/**
 * 设备
 * @param data
 */
export const userDeviceAPI = (data: userDeviceListModel) => {
    return post({
        url: API_ADDRESS.USER__DEVICE_LIST,
        data: builderRequestParam(data)
    })
}
/**
 * 用户api key 列表
 */
export const userAPIKEYAPI = (data: userApiKeyFilterModel) => {
    return post({
        url: API_ADDRESS.USER_API_KEY_LIST,
        data: builderRequestParam(data)
    })
}

/**
 * 验证2fa 验证码
 */
export const verify2FACORRECT = (data: basicAccountModel) => {
    return post({
        url: API_ADDRESS.VERIFY_2FA_CORRECT,
        data: builderRequestParam(data)
    })
}

/**
 * 用户退出登录
 */
export const userLogoutAPI = () =>{
    return post({
        url: API_ADDRESS.USER_LOGOUT,
        data: builderRequestParam(null)
    })
}

/**
 * 获取调用支付列表数据
 * @param data
 */
export const getCallPaymentListAPI = (data: payAttachFilter) =>{
    return post({
        url: API_ADDRESS.GET_CALL_PAYMENT,
        data: builderRequestParam(data)
    })
}

/**
 * 流水账单
 * @param data
 */
export const getBillingListAPI = (data: payAttachFilter) => {
    return post({
        url: API_ADDRESS.BILLING_LIST,
        data: builderRequestParam(data)
    })
}

export const verifyPaySuccessAPI = (data: OneField) => {
    return post({
        url: API_ADDRESS.VERIFY_PAY_SUCCESS,
        data: builderRequestParam(data)
    })
}


/**
 * 根据ip 地址获取地址信息
 * @param ip
 */
export const getIPAddressAPI =  (ip:string) => {
    return get<getResultAddress>({
            url: API_ADDRESS.EXTERNAL_URL + ip + "?lang=zh-CN"
        }
    )
}

/**
 * 更换2fa 验证方式
 */
export const updateUser2FAMethod = () => {
    return post({
        url: API_ADDRESS.UPDATE_2FA_METHOD,
        data: builderRequestParam(null)
    })
}

/**
 * 获取首页数据
 */
export const getHomeDetail = () => {
    return post({
        url: API_ADDRESS.HOME_DETAIL,
        data: builderRequestParam(null)
    })
}

/**
 * 验证2fa的验证码是否验证成功
 */
export const verify2FACorrect = (data: basicAccountModel) => {
    return post({
        url: API_ADDRESS.VERIFY_2FA_CORRECT,
        data: builderRequestParam(data)
    })
}

/**
 * 修改邮箱账号
 * @param data
 */
export const updateEmailAccount = (data: basicAccountModel) => {
    return post({
        url: API_ADDRESS.BIND_ACCOUNT_LOGIN_METHOD,
        data: builderRequestParam(data)
    })
}
/**
 * 修改用户基础信息
 * @param data
 */
export const updateUserBasicDetail = (data:any) => {
    return post({
        url: API_ADDRESS.UPDATE_USER_BASIC,
        data: builderRequestParam(data)
    })
}

/**
 * 如果后台验证token 或 账号错误则直接返回登录页
 * @param code
 * @param router
 */
export function isResultLogin(code:number, router:any) {
    if (code === -1000) {
        router.push("/login")
    }
}

/**
 * 获取用户基础信息
 */
export function getUserDetail() {
     post({
        url: API_ADDRESS.USER_BASIC_DETAIL,
        data: builderRequestParam(null)
    }).then(res => {
            if (res.code === 200) {
                const userBasicDetail:User.saveUserInfo = res.data
                const token = userStore.getAppointUserToken()
                // @ts-ignore
                userBasicDetail.token = token
                userStore.saveLoginUserInfo(userBasicDetail)
                location.reload()
            }
     })
}

export function requestCallPayment(data: PayCallParam) {
    return post({
        url: API_PAY_ADDRESS.TRANSACTION,
        data: data
    })
}


export  function getResultImgUrl(imgUrl: string) {
    if (imgUrl.startsWith("http://") || imgUrl.startsWith("https://")) {
        return imgUrl;
    }
    return IMG_URI_ADDRESS + imgUrl;
}



// 函数用于检查IP地址是否为私有网络地址
export const isInternalIPAddress = (ip: string): boolean  => {
    if (ip === "127.0.0.1" || ip === "localhost") {
        return true
    }
    // 定义私有网络范围的正则表达式
    const privateNetworkRanges = [
        /^10\.\d{1,3}\.\d{1,3}\.\d{1,3}$/, // 10.0.0.0/8
        /^172\.(1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}$/, // 172.16.0.0/12 到 172.31.0.0/12
        /^192\.168\.\d{1,3}\.\d{1,3}$/, // 192.168.0.0/16
        // 如果有需要，可以添加更多私有网络范围
    ];
    // 检查IP地址是否匹配任何一个私有网络范围
    for (const range of privateNetworkRanges) {
        if (range.test(ip)) {
            return true;
        }
    }
    return false;
}

